# Definition for a binary tree node.
class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right


from typing import *


class Solution:
    def kthLargestLevelSum(self, root: Optional[TreeNode], k: int) -> int:
        cnt = Counter()

        def f(node, h):
            if node is None:
                return
            cnt[h] += node.val
            f(node.left, h + 1)
            f(node.right, h + 1)

        f(root, 0)
        ls = [v for k, v in cnt.items()]
        ls.sort(reverse=True)
        return ls[k - 1] if k < len(ls) else -1
